﻿using System;
using System.Reflection;
using System.Web.UI;
using Components.Configuration;
using Components.Data.UI.Controls.ControlBuilders;

namespace Components.Data.UI.Controls
{
  internal class ControlBindingFactory
  {
    public virtual ControlBinding Create(String controlID, String parentControlID, String type, ControlBindingArgs args)
    {
      ControlBuilderReference controlBuilderReference = ConfigurationManager.Instance.ControlBuilderReferences[type];

      String typeInfo = controlBuilderReference.Type;

      if (!(!String.IsNullOrEmpty(typeInfo) && typeInfo.Contains(",") && !typeInfo.StartsWith(",") && !typeInfo.EndsWith(",")))
        return null;

      String assemblyName = typeInfo.Substring((typeInfo.IndexOf(",") + 1)).Trim();
      if (String.IsNullOrEmpty(assemblyName))
        return null;

      String typeName = typeInfo.Substring(0, typeInfo.IndexOf(",")).Trim();
      if (String.IsNullOrEmpty(typeName))
        return null;

      Assembly loadedAssembly = Assembly.Load(assemblyName);
      if (loadedAssembly == null)
        return null;

      Type loadedType = loadedAssembly.GetType(typeName);
      if (loadedType == null)
        return null;

      Object loadedObject = Activator.CreateInstance(loadedType);
      if (loadedObject == null || !(loadedObject is IControlBuilder))
        return null;

      IControlBuilder controlBuilder = loadedObject as IControlBuilder;
      Control control = controlBuilder.Build(args);
      control.ID = controlID;
      return new ControlBinding(control, parentControlID);
    }
  }
}